import { login, getInfo } from '@/api/login'
import { getToken, getUserID, setToken, removeToken, setUserID, removeUserId, setCode, getCode } from '@/utils/auth'

const user = {
  state: {
    token: getToken(), // token
    user_id: getUserID(), // guid
    last_time: '', // 最后登录时间
    username: '', // 用户名
    roles: '', // 角色
    code: getCode(), // 区分管理员和渠道
    avatar: ''
  },

  mutations: {
    // token
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    // guid
    SET_USER_ID: (state, user_id) => {
      state.user_id = user_id
    },
    // 用户名
    SET_NAME: (state, name) => {
      state.username = name
    },
    // 用户角色
    SET_ROLE: (state, roles) => {
      state.roles = roles
    },
    // 最后登录时间
    SET_LAST_TIME: (state, last_time) => {
      state.last_time = last_time
    },
    // 最后登录时间
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      userInfo.code = userInfo.code.trim()
      userInfo.username = userInfo.username.trim()
      userInfo.password = userInfo.password.trim()
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          // 把登录信息写入缓存
          setToken(response.token)
          setUserID(response.guid)
          setCode(response.code)
          // 将用户信息写入vuex
          commit('SET_TOKEN', response.token)
          commit('SET_USER_ID', response.guid)
          commit('SET_CODE', response.code)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }, guid) {
      // console.log(guid)
      var param = {
        guid: state.user_id,
        code: state.code
      }
      return new Promise((resolve, reject) => {
        getInfo(param).then(response => {
          // 拉取用户信息成功，将数据写入vuex
          if (response) {
            // 用户名
            commit('SET_NAME', response.username)
            // 角色
            commit('SET_ROLE', response.role)
            // 最后登录时间
            commit('SET_LAST_TIME', response.last_time)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit, state }) {
      // 清楚token
      commit('SET_TOKEN', '')
      // 清除角色
      commit('SET_ROLE', '')
      // 清除guid
      commit('SET_USER_ID', '')
      // 清除缓存
      removeToken()
      // 清除user_id
      removeUserId()
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
